package com.iepacj.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * Created by iEpac on 16/4/12.
 */
public class CuratorApi {


    public static void main(String[] args) throws InterruptedException {

        String connStr = "localhost:2181,localhost:2182";

        /**
         * 重试策略, 主要有四种实现
         * 1. ExponentialBackoffRetry
         * 2. RetryNTimes
         * 3. RetryOneTime
         * 4. RetryUntilElapsed
         */
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 3);

        /**
         * 使用CuratorFrameworkFactory类来创建客户端
         */
        //CuratorFramework curator = CuratorFrameworkFactory.newClient(connStr, retryPolicy);

        CuratorFramework curator = CuratorFrameworkFactory.builder()
                .connectString(connStr)
                .sessionTimeoutMs(3000)
                .connectionTimeoutMs(3000)
                .retryPolicy(retryPolicy)
                .namespace("curator")
                .build();

        curator.start();

        try {

            String path = "/create_node";

            Stat stat = curator.checkExists().forPath(path);
            if (stat != null) {
                curator.delete().forPath(path);
            }


            // 默认创建持久节点
            curator.create().forPath(path, "this is content".getBytes());

            // withMode 创建临时节点
            curator.create().withMode(CreateMode.EPHEMERAL).forPath("/create_node_ephe");

            // 自动递归创建父节点
            curator.create().creatingParentsIfNeeded().forPath("/create_di_gui/children");


        } catch (Exception e) {
            e.printStackTrace();
        }


        Thread.sleep(Integer.MAX_VALUE);

    }


}